import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from "taro-ui";
import {Block, Image, ScrollView, Text, View} from "@tarojs/components";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {GetRequest, vcmonitor} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {CATEGORY_GROUP, RESOURCE_URL, SHOP_PAGE, TARO_ENV} from "../../constants/api";
import {location as localtionServer} from "../../utils/location.service";
import { h5Wx } from '../../utils/h5.service';
import './index.scss'

type PageState = {
  loadMoreStatus: "more" | "loading" | "noMore"
  bottomView: any
  tableData: any
  groupList: any
  categoryId: any
}

export default class Index extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    bottomView: '',
    categoryId: '',
    tableData: [],
    groupList: []
  }

  async UNSAFE_componentWillMount() {
    await vcmonitor(this)
    if(process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
  }

  async componentDidShow() {
    const uuid = Taro.getCurrentInstance().router.params.uuid || ''
    let groupList = await newHttp.get(CATEGORY_GROUP)
    if (groupList && groupList.data && groupList.data.length > 0) {
      groupList = groupList.data
      let categoryId
      let i = 0
      if (uuid) {
        const index = groupList.findIndex(item => item.uuid === uuid)
        if (index > -1) {
          i = index
          categoryId = groupList[index].id
        } else {
          categoryId = groupList[0].id
        }
      } else {
        categoryId = groupList[0].id
      }
      this.setState({ bottomView: 'bottomView' + i,groupList, categoryId }, async ()=>{
        await this.location()
      })
    } else {
      await this.location()
    }
  }

  async location(){
    if (!Taro.getStorageSync('locationData')) {
      localtionServer.getLocation().then(async (res: any) => {
        if (res) {
          Taro.setStorageSync('locationData', res);
        }
        this.setState({ tableData: await this.getData() })
      })
    } else {
      this.setState({ tableData: await this.getData() })
    }
  }

  async getData(){
    const tableData = await newHttp.post(SHOP_PAGE, { categoryId: this.state.categoryId, page: this.page, size: 10})
    if (tableData && tableData.data) {
      this.total = tableData.totalRows
      if (this.page * 10 < this.total) {
        this.setState({ loadMoreStatus: 'more' })
      } else {
        this.setState({ loadMoreStatus: 'noMore' })
      }
      return tableData.data
    } else {
      this.setState({ loadMoreStatus: 'noMore' })
    }
    return []
  }

  page = 1
  total = 0

  async onReachBottom() {
    if (this.page * 10 < this.total) {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const tableData = await this.getData()
      const old = this.state.tableData
      if (tableData) {
        this.setState({tableData: [...old, ...tableData]})
      }
    }
  }

  categoryListClick(categoryId, index) {
    try {
      if (this.state.categoryId === categoryId) {
        return false
      }
      Taro.showLoading({title: '加载中...'});
      this.page = 1
      this.setState({bottomView: 'bottomView' + index,categoryId, loadMoreStatus: 'loading', tableData: []}, async () => {
        const tableData = await this.getData()
        this.setState({tableData})
        Taro.hideLoading()
      })
    } catch (e) {
      Taro.hideLoading()
    }
  }

  formatLink(path){
    const index = path.indexOf('/')
    if (index === -1 || index > 0) {
      path = '/' + path
    }
    return path
  }

  async jump(item) {
    const path = this.formatLink(item.link)
    if (process.env.TARO_ENV === 'weapp' && !!item.type) {
      return Taro.navigateToMiniProgram({
        appId: item.appid, // b小程序的appID 两个小程序必须关联在同一个公众号下
        path, // 跳转到b的页面
        envVersion: 'trial', //跳转到b的正式版
        fail: (res) => {
          if (res.errMsg === 'navigateToMiniProgram:fail cancel') {
            return false
          }
          if (res.errMsg === 'navigateToMiniProgram:fail invalid appid') {
            return this.displayModel('appid错误')
          } else if (res.errMsg.endsWith('navigate to myself')){
            return this.displayModel('您已在要跳转的小程序')
          } else {
            return this.displayModel(res.errMsg)
          }
        }
      })
    }
    try {
      await Taro.navigateTo({
        url: path
      })
    } catch (e) {
      if (e.errMsg.endsWith(' is not found') || e.errMsg.startsWith('navigateTo:fail Can not find proper registered route for')) {
        this.displayModel('链接不存在')
        setTimeout(() => Taro.navigateBack({delta: 1}), 2000)
      }
    }
  }

  displayModel(content) {
    Taro.showModal({
      content,
      title: '',
      showCancel: false
    })
  }

  render() {
    const {loadMoreStatus, tableData, groupList, categoryId, bottomView} = this.state
    return (
      <View className='site-list-root'>
        <GzhAuth />
        {groupList.length > 0 && <ScrollView scrollIntoView={bottomView} scrollX enable-flex className='subNav'>
          <View className='nav-box'>
            {groupList.map((item, index) =>
              <Block key={index}>
                <View onClick={this.categoryListClick.bind(this, item.id, index)} id={'bottomView' + index} className={`nav-item ${index === groupList.length - 1 && `${TARO_ENV + '-nav-item-last'}`} ${categoryId === item.id ? 'active' : ''}`}>
                  {item.name}
                  {categoryId === item.id && <View className='active-line' />}
                </View>
                {index === groupList.length -1 && <Text decode>&nbsp;</Text>}
              </Block>
            )}
          </View>
        </ScrollView>}
        <View className='tableData-wrapper'>
          {tableData.length > 0 && tableData.map((item, index) => <View key={index} className={`site-list-item ${index === 0 && 'site-list-item-first'}`}>
            <Image src={item.logo} mode='widthFix' className='img' />
            <View className='right-items'>
              <View className='items-top'>
                <View className='items-title'>{item.name}</View>
                {(!item.type || (process.env.TARO_ENV !== 'h5' && !!item.type)) && <View className='items-btn' onClick={this.jump.bind(this, item)}>进店逛逛</View>}
                {process.env.TARO_ENV === 'h5' && !!item.type && <wx-open-launch-weapp
                  username={item.mp_original_id || ''}
                  path={this.formatLink(item.link)}
                >
                  <script type='text/wxtag-template'>
                    <div style='white-space: nowrap; display: flex; padding: 3px 6px; align-items: center; border-radius: 48px; justify-content: center; color: #888; font-size: 12px; border: 1px solid #888;'>进店逛逛</div>
                  </script>
                </wx-open-launch-weapp>}
              </View>
              <View className='items-top' style='margin-top: 6px'>
                <View className='items-sub-title'>{item.description}</View>
                {!!item.distance && item.distance !== '0km' && <View className='location'><AtIcon size='14' color='#888' value='icon icon-weizhi-01-01' /><Text className={`distance ${TARO_ENV + '-distance'}`}>{item.distance}</Text></View>}
              </View>
            </View>
          </View>)}
        </View>
        {loadMoreStatus !== 'loading' && tableData.length <= 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
          <View className='text'>什么都没有,去看看别的吧~</View>
        </View>}
      </View>
    )
  }
}
